package customs

import (
    "crypto/tls"
	"wxsdk/wxpay/utils/mapstruct"
	"github.com/astaxie/beego"
)

type RepushRequest struct {
	AppId         string   `xml:"appid,omitempty"`          //公众账号ID
	MchId         string   `xml:"mch_id,omitempty"`         //商户号
	Customs       string   `xml:"customs,omitempty"`        //海关
	MchCustomsNo  string   `xml:"mch_customs_no,omitempty"` //商户海关备案号
	OutTradeNo    string   `xml:"out_trade_no,omitempty"`   //商户订单号
	Sign          string   `xml:"sign,omitempty"`           //签名
}

type RepushResponse struct {
    CustomsBaseResponse `xml:",innerXml,omitempty"`
	State           string `xml:"state,omitempty"`          //状态码
	TransactionId   string `xml:"transaction_id,omitempty"` //微信支付订单号
	OutTradeNo      string `xml:"out_trade_no,omitempty"`   //商户订单号
	SubOrderNo      string `xml:"sub_order_no,omitempty"`   //商户子订单号
	SubOrderId      string `xml:"sub_order_id,omitempty"`   //微信子订单号
	ModifyTime      string `xml:"modify_time,omitempty"`    //最后更新时间
	Explanation     string `xml:"explanation,omitempty"`    //申报结果说明
}

func RepushApp(appSecret string, request *RepushRequest, crt,key string)(rsp *RepushResponse, err error){
	reqURL := "https://api.mch.weixin.qq.com/cgi-bin/mch/newcustoms/customdeclareredeclare"
	cert, e := tls.X509KeyPair([]byte(crt), []byte(key))
	if e != nil {
		err = e
		return
	}
	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{cert},
	}
	sdk := NewSDK(reqURL, request.AppId, request.MchId, appSecret, tlsConfig)
	params := mapstruct.Struct2Map(request, "xml")
	rspMap, e := sdk.Execute(params)
	if e != nil {
	   beego.Debug("MicroAppPay sdk.Execute:", e.Error())
	   err = e
	   return
	}
	microRsp := new(RepushResponse)
	err = mapstruct.Map2Struct(rspMap, microRsp, "xml")
	if err == nil {
	   rsp = microRsp
	}
	return
}

